package com.dms.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.dms.bean.Announce;
import com.dms.util.DBUtil;


public class AnnounceDao {
	private static DBUtil	db	= new DBUtil();
	public static boolean add(Announce announce) {
		boolean val = false;
		if (announce!=null) {
			String sql = "insert into announce (content,title,date) values(?,?,?)";
			try {
				db.update(sql,announce.getContent(), announce.getTitle(), announce.getDate());
				val=true;
			}
			catch (Exception e) {
				e.printStackTrace();
			}
			try {
				db.close();
			}
			catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return val;
	}
	public static ArrayList<Announce> list() {
		ArrayList<Announce> announces = new ArrayList<Announce>();
		String sql = "select * from announce order by date desc";
		try {
			ResultSet rs = db.query(sql);
			while (rs.next()) {
				announces.add(new Announce(rs.getInt("annID"),rs.getString("title"),rs.getString("content"),rs.getTimestamp("date")));
			System.out.print(rs.getInt("annID"));
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		try {
			db.close();
		}
		catch (SQLException e) {
			e.printStackTrace();
		}
		return announces;
	}
	
	public static Announce find(int annID) {
		boolean val = false;
		Announce ann = new Announce();
		if (annID >=0) {
			String sql = "select title,content,date from announce where annID=?";
			ResultSet rs = null;
			try {
				rs = db.query(sql, annID);
				val = (rs != null && rs.next()) ? true : false;
				if (val) {
					ann.setAnnID(annID);
					ann.setTitle(rs.getString("title"));
					ann.setDate(rs.getTimestamp("date"));
					ann.setContent(rs.getString("content"));
				}
			}
			catch (Exception e) {
				val = false;
				e.printStackTrace();
			}
			try {
				db.close();
			}
			catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return ann;
	}
	public static boolean save(Announce announce) throws Exception {
		boolean var = false;
		try {
			if (announce != null) {
				String sql = "update announce set content=?,title=?,date=? where annID =?";
				db.update(sql, announce.getContent(), announce.getTitle(), announce.getDate(), announce.getAnnID());
				var = true;
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		try {
			db.close();
		}
		catch (SQLException e) {
			e.printStackTrace();
		}
		return var;
	}
	public static boolean delete(int annID) {
		boolean var = false;
		try {
				String sql = "delete from announce where annID =?";
				db.update(sql, annID);
				var = true;
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		try {
			db.close();
		}
		catch (SQLException e) {
			e.printStackTrace();
		}
		return var;
	}
}
